package org.nahtanoj.contacts;

public class ContactsSync {
	public ContactStore csd;
	public ContactStore csj;
	public ContactStore csc;

	public ContactsSync(ContactStore csd, ContactStore csj, ContactStore csc) {
		this.csd = csd;
		this.csj = csj;
		this.csc = csc;
		this.csd.load();
		this.csj.load();
		this.csc.load();
		ContactMatch cm = new ContactMatch();
		cm.match(csd, csj);
		cm.match(csd, csc);
		addDocsToMail(this.csj, "J"); addDocsToMail(this.csc, "C");
		addMailToDocs(this.csj, "J"); addMailToDocs(this.csc, "C");
		modDocsToMail(this.csj, "J"); modDocsToMail(this.csc, "C");
		this.csd.save();
	}

	private void addDocsToMail(ContactStore mailStore, String user) {
		for (String s : mailStore.getNewDocs().keySet()) {
			Contact dc = mailStore.getNewDocs().get(s);
			if (dc.getContactSync() != null && dc.getContactSync().toUpperCase().contains(user.toUpperCase())) {
				if (dc.isValid().length() == 0) {
					mailStore.add(dc);
				} else {
					dc.updateError();
				}
			}
		}
		mailStore.save();
	}

	private void addMailToDocs(ContactStore mailStore, String user) {
		for (String s : mailStore.getNewMail().keySet()) {
			Contact c = mailStore.getNewMail().get(s);
			c.setContactSync(user.toUpperCase());
			this.csd.add(c);
		}
	}

	private void modDocsToMail(ContactStore csc2, String user) {
		for (String s : csc2.getMatched().keySet()) {
			Contact dc = csc2.getMatched().get(s);
			if (dc.getMatch().getContactSync() == null || !dc.getMatch().getContactSync().toUpperCase().contains(user.toUpperCase())) {
				csc2.drop(dc);
			}
			dc.updateFromMatch();
		}
		for (String s : csc2.getContacts().keySet()) {
			Contact c = csc2.getContacts().get(s);
			c.updateContactSync(user);
		}
		csc2.save();
	}
}
